//
//  HDMapVC.m
//  HDWuDaDaoServiceCenter
//
//  Created by HDNiuKuiming on 2017/4/8.
//  Copyright © 2017年 HDNiuKuiming. All rights reserved.
//

@interface HDMapInfo : NSObject

@property (nonatomic, copy) NSString *height;
@property (nonatomic, copy) NSString *width;
@property (nonatomic, copy) NSString *map_addr;
@property (nonatomic, copy) NSString *title;

+ (instancetype)mapinfoWithDict:(NSDictionary *)dict;

@end

@implementation HDMapInfo

+ (instancetype)mapinfoWithDict:(NSDictionary *)dict
{    return [[self alloc] initWithDict:dict]; }

- (instancetype)initWithDict:(NSDictionary *)dict
{
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dict]; // 字典的快速赋值，需要特殊处理一下保留字段和未声明但是字典中有的字段
    }
    return self;
}

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    if([key isEqualToString:@"id"]) {
    }
}


@end


#import "HDMapVC.h"
#import "HD_NKM_MapView+Download.h"
#import "HDMapObj.h"
#import "HDPlayerView.h"
#import "HDMuseumIntrodeceVC.h"
#import "HDRootAudioVC.h"
#import "HDMapLargeImgVC.h"
#import "HDWebVC.h"
#import "HD_NKM_Mediator.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVCaptureDevice.h>

@interface HDMapVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    HDDeclare *declare;
    BOOL isReceive11;
    __weak IBOutlet UIView *cameraView;
}

@property (weak, nonatomic) IBOutlet UIView *mapBgView;
@property (weak, nonatomic) IBOutlet UIView *playerBgView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;

@property (strong, nonatomic) HD_NKM_MapView *mapView1;
@property (weak, nonatomic) IBOutlet UIView *poiBigImgBGView;
@property (weak, nonatomic) IBOutlet UIImageView *bigBgImgView;
@property (nonatomic, strong) NSString *myFloor;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) HDMapInfo *mapInfo;
@property (nonatomic, strong) HDPlayerView *playerView;
@property (nonatomic, strong) NSString *nowBeaconStr; // 当前蓝牙号


@end

@implementation HDMapVC

#pragma mark
#pragma mark -------- Init Methods --------

- (void)viewDidLoad {
    [super viewDidLoad];
    _myFloor = [NSString stringWithFormat:@"%lil", (long)_museumID.integerValue];
    declare = [HDDeclare sharedDeclare];
    _dataArray  = [NSMutableArray new];
    _myFloor    = _museumID;
    isReceive11 = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToPlayer:) name:Map_POI_Push_To_Player object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playToEndNotification) name:kPlayer_Play_To_End_Notification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beaconLocateAction:) name:iBeacon_Array_Send_Notification object:nil];
    
    [self poiRequestAction];
    [self playViewInit]; // 播放UI
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _nowBeaconStr = nil;
    
    [HD_NKM_Mediator setNowVCDescription:NSStringFromClass([self class])];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_playerView pauseAudioAction];
    [HD_NKM_Mediator setNowVCDescription:nil];
}

- (void)playViewInit {
    [_playerView removeFromSuperview];
    self.playerView = nil;
    
    _playerView = [[[NSBundle mainBundle] loadNibNamed:@"HDPlayerView" owner:self options:nil] lastObject];
    [_playerBgView addSubview:_playerView];
    [_playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_playerBgView).with.offset(0);
        make.right.equalTo(_playerBgView).with.offset(0);
        make.left.equalTo(_playerBgView).with.offset(0);
        make.bottom.equalTo(_playerBgView).with.offset(0);
    }];
}

- (void)poiRequestAction {
    if (_museumID.length == 0)
        return;
    
    HDRequestObj *loginObj = [[HDRequestObj alloc] init];
    NSString *urlPath = [NSString stringWithFormat:@"%@g=mapi&m=Contentinfo&a=exhibits_by_museum", HTTP_Request_URL_Prefix];
    NSDictionary *parameters = @{@"museum_id": _museumID,
                                 @"device_id": [[HDDeclare sharedDeclare] userPhoneID],
                                 @"language": @"CHINESE"};
    
    [loginObj requestGetPath:urlPath Parameter:parameters withVC:self timeout:5];
    loginObj.myDataBlock = ^(NSDictionary *allDic){
        
        NSString *loginCode = allDic[@"status"];
        if (loginCode.integerValue == 1) {
            NSDictionary *dataDic = allDic[@"data"];
            NSDictionary *mapInfoDic = dataDic[@"museum_info"];
            _mapInfo = [HDMapInfo mapinfoWithDict:mapInfoDic];
            _nameLabel.text = _mapInfo.title;

            NSArray *mapObjArray = dataDic[@"exhibit_info"];
            [_dataArray removeAllObjects];
            for (NSInteger i=0;i<mapObjArray.count;i++) {
                NSDictionary *objDic = mapObjArray[i];
                HDMapObj *obj = [HDMapObj mapPoiWithDict:objDic];
                [_dataArray addObject:obj];
            }
            [self threeMapInit:1]; // 地图初始化
        }
        else {
            // 加载失败，返回
            NSString *tipStr = allDic[@"msg"];
            if (tipStr.length > 6)
                tipStr = [NSString stringWithFormat:@"%@\n%@", [tipStr substringToIndex:6], [tipStr substringFromIndex:6]];
            
            [LCCoolHUD showFailure:tipStr zoom:NO shadow:YES];
            [self backAction:nil];
        }
    };
}

#pragma mark
#pragma mark -------- Mapview Delegate --------

- (void)threeMapInit:(NSInteger)nowTag
{
    dispatch_async(dispatch_get_main_queue(), ^{
        CGSize mapSize = CGSizeMake(_mapInfo.width.floatValue/8.0, _mapInfo.height.floatValue/8.0); //瓦片地图大小
        CGFloat miniScle = MAX(mapSize.height, mapSize.width)/MIN(mapSize.height, mapSize.width);
        LOG(@"Local Map height%f",self.view.bounds.size.height);
        
        self.mapView1 = [[HD_NKM_MapView alloc] initWithFrame:CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height-64) contentSize:mapSize];

        self.mapView1.dataSource = self;
        self.mapView1.mapViewdelegate = self;
        self.mapView1.minimumZoomScale = miniScle;
        self.mapView1.zoomScale = miniScle;
        self.mapView1.levelsOfZoom = 3;
        self.mapView1.levelsOfDetail = 3;
        self.mapView1.maximumZoomScale = 6;
        self.mapView1.backgroundColor = [UIColor clearColor];
        self.mapView1.contentOffset = CGPointZero;
        [self.mapBgView insertSubview:_mapView1 atIndex:0];
        [self showAllAnn:_mapView1 withFloor:_myFloor];
        self.mapView1.urlPrefix = _mapInfo.map_addr;
        self.mapView1.floorStr = _myFloor; // 用于存放在线加载的瓦片
        
        NSString *bgImgPath = [NSString stringWithFormat:@"%@img.png",_mapView1.urlPrefix];
        [_mapView1 initMinMapImage:bgImgPath];
        _mapView1.mapItemPath = [NSString stringWithFormat:@"%@/Resource/WebMap/%@", kCachePath, _myFloor]; // 瓦片地图的存放地址
        [_mapView1 performSelector:@selector(downloadFirstLevel) withObject:nil afterDelay:0.5];
    });
}


- (void)showAllAnn:(HD_NKM_MapView *)mapTemp withFloor:(NSString *)floor
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_dataArray.count == 0)
        { return ; }
        HDAnnotation * ann = nil;
        NSMutableArray *myannotions = [NSMutableArray arrayWithCapacity:_dataArray.count];
        for (HDMapObj *point in _dataArray)
        {
            /*注意，在HD_LD_ClusterAlgorithm类中的宏定义PointParameter的值要与下面计算x,y时所除倍数8.0一致*/
            CGFloat x = ([point.axis_x floatValue]/8.0f)*mapTemp.zoomScale;
            CGFloat y = ([point.axis_y floatValue]/8.0f)*mapTemp.zoomScale;
            if (x==0 || y == 0) // 无坐标的点不处理
                continue;
            
            ann = [HDAnnotation annotationWithPoint:CGPointMake(x, y)];
            ann.originalPoint = CGPointMake(point.axis_x.floatValue, point.axis_y.floatValue);
//            ann.identify = point.exhibit_id;
            ann.identify = [NSString stringWithFormat:@"%ld",[_dataArray indexOfObject:point]];
            ann.beaconNum= point.blue_teeth_id.integerValue;
            ann.poiImgPath = point.map_img_path;
            ann.type = point.type;
            ann.isPlay   = kPlay_Status_No;
            [mapTemp addAnnotation:ann animated:YES];
            [myannotions addObject:ann];
        }
        
        
        [mapTemp addClusterAnnotions:myannotions];
    });
}

// 当瓦片需要实时下载时候，使用以下方法，如果是zip包下载地图，则修改一下路径
- (UIImage *)mapView:(HDMapView *)mapView
         imageForRow:(NSInteger)row
              column:(NSInteger)column
               scale:(NSInteger)scale
{
    NSString *scaleFolder = @"125";
    if(scale == 2)
        scaleFolder = @"250";
    else if(scale == 4)
        scaleFolder = @"500";
    else if(scale > 4)
        scaleFolder = @"1000";
    
    NSString *suffixPath = [NSString stringWithFormat:@"1_%@_%ld_%ld.png",scaleFolder, (long)column,(long)row];
    NSString *name = [NSString stringWithFormat:@"%@/Resource/WebMap/%@/1_%@_%ld_%ld.png", kCachePath,_myFloor,scaleFolder, (long)column,(long)row];
    UIImage *myImage = [UIImage imageWithContentsOfFile:name];
    
    // 如果myImage是nil，说明在本地并没有存放，存入数组，多线程请求和下载，下载完成后通知地图刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        if (myImage == nil)
        {  [_mapView1 recordItemToSet:suffixPath]; }
    });
    
    return myImage;
}

- (void)pushToPlayer:(NSNotification*)note
{
    if (![self.navigationController.topViewController isKindOfClass:[self class]])
        return;
    
    HDAnnotation *noteAnn  = [note object];
    NSPredicate *preA  = [NSPredicate predicateWithFormat:@"SELF.exhibit_id == %@ && SELF.type == %@", noteAnn.identify, noteAnn.type];
    NSArray *nowArrayA = [_dataArray filteredArrayUsingPredicate:preA];
    
    if (nowArrayA.count == 0)
        return;
    
    HDMapObj *obj = nowArrayA[0];
    [self loadOnLineRes:obj];
}


- (void)playToEndNotification {
    _playerBgView.hidden = YES;
    _poiBigImgBGView.hidden = YES;
    [self adjustCameraViewLocationY:20];
}

- (void)loadOnLineRes:(HDMapObj *)obj {
    if ([obj.type.uppercaseString isEqualToString:@"SCENE"]) { // 用于场景
        UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        HDMapLargeImgVC *VC = [board instantiateViewControllerWithIdentifier:@"HDMapLargeImgVC"];
        VC.sceneObj = obj;
        [self.navigationController pushViewController:VC animated:YES];
        _poiBigImgBGView.hidden = YES;
    }
    else {
        _playerBgView.hidden = NO;
        [_playerView playItem:obj];
        [_playerView.leftImgView sd_setImageWithURL:[NSURL URLWithString:obj.route_img_path] placeholderImage:[UIImage imageNamed:@"player_default"]];
        _playerView.nameLabel.text = obj.title;
        [self openBgImgView:obj];
        
        CGFloat cameraY = _playerView.frame.size.height + _bigBgImgView.frame.size.width;
        [self adjustCameraViewLocationY:cameraY];
    }
}

- (IBAction)closeBgImgView:(id)sender {
    _poiBigImgBGView.hidden = YES;
    CGFloat cameraY = _playerView.frame.size.height;
    [self adjustCameraViewLocationY:cameraY];
}

- (IBAction)openBgImgView:(HDMapObj *)obj {
    _poiBigImgBGView.hidden = NO;
    [_bigBgImgView sd_setImageWithURL:[NSURL URLWithString:obj.img_url] placeholderImage:[UIImage imageNamed:@"bigImgDefault"]];
    
    [_playerView.showOrHideBigImgViewBgtn removeTarget:self action:@selector(showOrHideBigImg) forControlEvents:UIControlEventTouchUpInside];
    [_playerView.showOrHideBigImgViewBgtn addTarget:self action:@selector(showOrHideBigImg) forControlEvents:UIControlEventTouchUpInside];
}


- (void)showOrHideBigImg
{
    _poiBigImgBGView.hidden = !_poiBigImgBGView.hidden;
    if (_poiBigImgBGView.hidden == NO) {
        CGFloat cameraY = _playerView.frame.size.height + _bigBgImgView.frame.size.width;
        [self adjustCameraViewLocationY:cameraY];
    }
}

- (void)adjustCameraViewLocationY:(CGFloat)locY
{
    [cameraView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).with.offset(-locY);
    }];
}

#pragma mark
#pragma mark -------- Beacon Methods --------

- (void)beaconLocateAction:(NSNotification *)noti {
    NSString *beaconStr = [NSString stringWithFormat:@"%@",noti.object];
    if (beaconStr.integerValue == _nowBeaconStr.integerValue)
        return;
    if ( isReceive11 == YES) {
        if (beaconStr.integerValue == 7 || beaconStr.integerValue == 8 || beaconStr.integerValue == 9 || beaconStr.integerValue == 10)
            return;
    }
    if (beaconStr.integerValue == 11 )
        isReceive11 = YES;
    if (beaconStr.integerValue == 6 )
        isReceive11 = NO;
    
    BOOL isNowFloor = NO;
    for (HDMapObj *obj in _dataArray) {
        if (obj.blue_teeth_id.integerValue == beaconStr.integerValue)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                _nowBeaconStr = beaconStr;
                [_mapView1 changeMorePin:beaconStr.integerValue];
            });
            isNowFloor = YES;

            break;
        }
    }
    
    if (isNowFloor == NO) { // 不是当前楼层，请求数据，确定是否提示
        _nowBeaconStr = beaconStr;
        [self requestBeaconNum:beaconStr];
    }
}

- (void)requestBeaconNum:(NSString *)str
{
    if(str==nil || str.length == 0)
        return;
    
    HDRequestObj *loginObj = [[HDRequestObj alloc] init];
    NSString *urlPath = [NSString stringWithFormat:@"%@g=mapi&m=Ticket&a=is_blueteeth_id_valid", HTTP_Request_URL_Prefix];
    NSDictionary *parameters = @{@"blueteeth_id": str,
                                 @"language":@"CHINESE",
                                 @"device_id": [[HDDeclare sharedDeclare] userPhoneID]};
    
    [loginObj requestGet:urlPath Parameter:parameters];
    loginObj.myDataBlock = ^(NSDictionary *allDic){
        
        NSString *loginCode = allDic[@"status"];
        if (loginCode.integerValue == 1) {
            NSDictionary *dataDic = allDic[@"data"];
            NSString *is_valid = dataDic[@"is_valid"];
            if (is_valid.integerValue == 1) {
                NSString *museum_name = dataDic[@"museum_name"];
                NSString *museumNewID = dataDic[@"museum_id"];

                NSString *tipStr = [NSString stringWithFormat:@"是否切换到%@", museum_name];
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:tipStr preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    _museumID = dataDic[@"museum_id"];
                    _nameLabel.text = museum_name;
                    _myFloor = [NSString stringWithFormat:@"%lil", (long)_museumID.integerValue];

                    [self mapviewClean];
                    [self playerClean];
                    [self poiRequestAction];
                    [self playViewInit];
                    _nowBeaconStr = nil;
                }];
                
                [alertVC addAction:cancelAction];
                [alertVC addAction:okAction];
                
                if(_museumID.integerValue != museumNewID.integerValue)
                    [self presentViewController:alertVC animated:YES completion:NULL];
            }
        }
    };
}

- (void)mapviewClean
{
    [_mapView1 removeAllAnnatations:NO];
    _mapView1.urlPrefix = nil;
    [_mapView1 removeFromSuperview];
    self.mapView1 = nil;
    
    isReceive11 = NO;
}

- (void)playerClean
{
    [_playerView removeFromSuperview];
    _playerView = nil;
}

#pragma mark
#pragma mark -------- Back Methods --------

- (IBAction)pushToComeraAction:(id)sender {
    //判断是否已授权
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied ||authStatus == AVAuthorizationStatusRestricted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [LCCoolHUD showFailure:@"相机未授权" zoom:NO shadow:NO];
        });
        return ;
    }
    
    // 判断是否可以打开相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
        
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [LCCoolHUD showFailure:@"你没有相机" zoom:NO shadow:NO];
        });
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self loadImageFinished:image];
}

- (void)loadImageFinished:(UIImage *)image
{
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    if (authStatus == PHAuthorizationStatusAuthorized) {
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            //写入图片到相册
            [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            
            NSLog(@"success = %d, error = %@", success, error);
            if (success)
                dispatch_async(dispatch_get_main_queue(), ^{
                    [LCCoolHUD showSuccess:@"保存成功" zoom:YES shadow:YES];
                });
        }];
    }
    
    else {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    //写入图片到相册
                    [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                } completionHandler:^(BOOL success, NSError * _Nullable error) {
                    
                    NSLog(@"success = %d, error = %@", success, error);
                }];
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [LCCoolHUD showFailure:@"相机未授权" zoom:NO shadow:NO];
                });
            }
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)backAction:(id)sender {
    // 判断是否是门票过来的
    BOOL isFromTicket = NO;
    for (UIViewController *VC in self.navigationController.viewControllers) {
        if ([VC isKindOfClass:[HDWebVC class]])
        {
            HDWebVC *tempVC = (HDWebVC *)VC;
            if (tempVC.webVCType == kWeb_VC_Type_Ticket) {
                [self.navigationController popToViewController:VC animated:YES];
                isFromTicket = YES;
            }
            
            break;
        }
    }
    if (isFromTicket == YES)
        return;
    
    // 判断是其他扫码页面过来的
    BOOL isBackToIntrodicde = NO;
    for (UIViewController *VC in self.navigationController.viewControllers) {
        if ([VC isKindOfClass:[HDRootAudioVC class]])
        {
            [self.navigationController popToViewController:VC animated:YES];
            isBackToIntrodicde = YES;
            break;
        }
    }
    
    if (isBackToIntrodicde == NO)
        [super back];
}

- (void)dealloc
{
    [self mapviewClean];
    [self playerClean];
}

@end
